import React from 'react';
import { 
  Dialog, 
  DialogTitle, 
  DialogContent, 
  DialogActions,
  Button,
  Typography,
  Box,
  Paper,
  Tabs,
  Tab,
  IconButton,
  Grid
} from '@mui/material';
import { Close as CloseIcon } from '@mui/icons-material';
import ReactECharts from 'echarts-for-react';
import type { EChartsOption } from 'echarts';

interface TabPanelProps {
  children?: React.ReactNode;
  index: number;
  value: number;
}

function TabPanel(props: TabPanelProps) {
  const { children, value, index, ...other } = props;

  return (
    <div
      role="tabpanel"
      hidden={value !== index}
      id={`visualization-tabpanel-${index}`}
      aria-labelledby={`visualization-tab-${index}`}
      {...other}
    >
      {value === index && (
        <Box sx={{ p: 3 }}>
          {children}
        </Box>
      )}
    </div>
  );
}

interface ModelVisualizationDialogProps {
  open: boolean;
  onClose: () => void;
  nodeId: string;
  metrics?: {
    accuracy: number;
    precision: number;
    recall: number;
    f1: number;
    confusion_matrix?: number[][];
    roc_curve?: {
      fpr: number[];
      tpr: number[];
      thresholds: number[];
      auc: number;
    }
  };
  feature_importance?: Record<string, number>;
}

const ModelVisualizationDialog: React.FC<ModelVisualizationDialogProps> = ({
  open,
  onClose,
  nodeId,
  metrics,
  feature_importance
}) => {
  const [tabValue, setTabValue] = React.useState(0);

  // 添加初始加载日志
  React.useEffect(() => {
    if (open) {
      console.log('=======================================');
      console.log('模型可视化对话框打开');
      console.log('接收的props:', {
        nodeId,
        metricsProvided: !!metrics,
        featureImportanceProvided: !!feature_importance,
        metricsKeys: metrics ? Object.keys(metrics) : [],
        rocCurveProvided: metrics?.roc_curve ? true : false,
        rocCurveKeys: metrics?.roc_curve ? Object.keys(metrics.roc_curve) : []
      });
      console.log('=======================================');
    }
  }, [open, nodeId, metrics, feature_importance]);

  const handleTabChange = (event: React.SyntheticEvent, newValue: number) => {
    setTabValue(newValue);
  };

  // 检查是否有可视化数据
  const hasConfusionMatrix = metrics?.confusion_matrix && metrics.confusion_matrix.length > 0;
  const hasRocCurve = metrics?.roc_curve && 
                     Array.isArray(metrics.roc_curve.fpr) && 
                     Array.isArray(metrics.roc_curve.tpr) && 
                     metrics.roc_curve.fpr.length > 0 && 
                     metrics.roc_curve.tpr.length > 0;
  const hasFeatureImportance = feature_importance && 
                              typeof feature_importance === 'object' && 
                              Object.keys(feature_importance).length > 0;

  // 打印一下是否有混淆矩阵、ROC曲线和特征重要性数据
  React.useEffect(() => {
    console.log('对话框组件接收到的数据：', {
      nodeId,
      metrics,
      feature_importance
    });
    
    console.log('对话框组件详细数据：', {
      nodeId,
      metrics: metrics ? {
        confusion_matrix: metrics.confusion_matrix ? `${metrics.confusion_matrix.length}x${metrics.confusion_matrix[0]?.length || 0}` : 'none',
        roc_curve: metrics.roc_curve ? {
          fpr: Array.isArray(metrics.roc_curve.fpr) ? `length: ${metrics.roc_curve.fpr.length}` : 'invalid',
          tpr: Array.isArray(metrics.roc_curve.tpr) ? `length: ${metrics.roc_curve.tpr.length}` : 'invalid',
          auc: metrics.roc_curve.auc
        } : 'none'
      } : 'none',
      feature_importance: feature_importance ? `${Object.keys(feature_importance).length} features` : 'none',
      hasConfusionMatrix,
      hasRocCurve,
      hasFeatureImportance
    });
  }, [metrics, feature_importance, hasConfusionMatrix, hasRocCurve, hasFeatureImportance, nodeId]);

  // 渲染混淆矩阵
  const renderConfusionMatrix = () => {
    if (!hasConfusionMatrix) return <Typography>没有可用的混淆矩阵数据</Typography>;

    const matrix = metrics!.confusion_matrix!;
    const isBinary = matrix.length === 2 && matrix[0].length === 2;
    
    if (isBinary) {
      // 二分类混淆矩阵 (2x2)
      const TN = matrix[0][0]; // 真阴性
      const FP = matrix[0][1]; // 假阳性
      const FN = matrix[1][0]; // 假阴性
      const TP = matrix[1][1]; // 真阳性
      
      // 计算各项指标
      const startTime = performance.now();
      
      // 计算敏感度（真阳性率）
      const sensitivity = TP / (TP + FN);
      
      // 计算特异度（真阴性率）
      const specificity = TN / (TN + FP);
      
      // 计算假阳性率
      const falsePositiveRate = FP / (FP + TN);
      
      // 计算假阴性率
      const falseNegativeRate = FN / (TP + FN);
      
      // 计算准确度
      const accuracy = (TP + TN) / (TP + TN + FP + FN);
      
      const endTime = performance.now();
      const calculationTime = (endTime - startTime).toFixed(2);
      
      return (
        <Box sx={{ display: 'flex', flexDirection: 'column', alignItems: 'center' }}>
          <Typography variant="h6" sx={{ mb: 3 }}>二分类混淆矩阵</Typography>
          
          <Grid container sx={{ width: '320px', mb: 3 }}>
            {/* 顶部标签 */}
            <Grid item xs={4}></Grid>
            <Grid item xs={4} sx={{ textAlign: 'center' }}>
              <Typography variant="subtitle2" sx={{ fontWeight: 'bold' }}>预测: 阴性 (0)</Typography>
            </Grid>
            <Grid item xs={4} sx={{ textAlign: 'center' }}>
              <Typography variant="subtitle2" sx={{ fontWeight: 'bold' }}>预测: 阳性 (1)</Typography>
            </Grid>
            
            {/* 第一行 - 真实阴性 */}
            <Grid item xs={4} sx={{ display: 'flex', alignItems: 'center' }}>
              <Typography variant="subtitle2" sx={{ fontWeight: 'bold' }}>实际: 阴性 (0)</Typography>
            </Grid>
            <Grid item xs={4} sx={{ p: 1 }}>
              <Paper 
                elevation={3} 
                sx={{ 
                  bgcolor: '#e8f5e9', 
                  p: 2, 
                  textAlign: 'center',
                  display: 'flex',
                  flexDirection: 'column',
                  height: '100px',
                  justifyContent: 'center'
                }}
              >
                <Typography variant="h6" sx={{ fontWeight: 'bold', color: '#2e7d32' }}>{TN}</Typography>
                <Typography variant="body2">真阴性 (TN)</Typography>
              </Paper>
            </Grid>
            <Grid item xs={4} sx={{ p: 1 }}>
              <Paper 
                elevation={3} 
                sx={{ 
                  bgcolor: '#ffebee', 
                  p: 2, 
                  textAlign: 'center',
                  display: 'flex',
                  flexDirection: 'column',
                  height: '100px',
                  justifyContent: 'center'
                }}
              >
                <Typography variant="h6" sx={{ fontWeight: 'bold', color: '#c62828' }}>{FP}</Typography>
                <Typography variant="body2">假阳性 (FP)</Typography>
              </Paper>
            </Grid>
            
            {/* 第二行 - 真实阳性 */}
            <Grid item xs={4} sx={{ display: 'flex', alignItems: 'center' }}>
              <Typography variant="subtitle2" sx={{ fontWeight: 'bold' }}>实际: 阳性 (1)</Typography>
            </Grid>
            <Grid item xs={4} sx={{ p: 1 }}>
              <Paper 
                elevation={3} 
                sx={{ 
                  bgcolor: '#ffebee', 
                  p: 2, 
                  textAlign: 'center',
                  display: 'flex',
                  flexDirection: 'column',
                  height: '100px',
                  justifyContent: 'center'
                }}
              >
                <Typography variant="h6" sx={{ fontWeight: 'bold', color: '#c62828' }}>{FN}</Typography>
                <Typography variant="body2">假阴性 (FN)</Typography>
              </Paper>
            </Grid>
            <Grid item xs={4} sx={{ p: 1 }}>
              <Paper 
                elevation={3} 
                sx={{ 
                  bgcolor: '#e8f5e9', 
                  p: 2, 
                  textAlign: 'center',
                  display: 'flex',
                  flexDirection: 'column',
                  height: '100px',
                  justifyContent: 'center'
                }}
              >
                <Typography variant="h6" sx={{ fontWeight: 'bold', color: '#2e7d32' }}>{TP}</Typography>
                <Typography variant="body2">真阳性 (TP)</Typography>
              </Paper>
            </Grid>
          </Grid>
          
          {/* 添加性能指标表格 */}
          <Paper 
            elevation={2}
            sx={{ 
              width: '100%', 
              maxWidth: '600px', 
              mb: 3, 
              p: 2,
              border: '1px solid #e0e0e0',
              borderRadius: 1
            }}
          >
            <Typography variant="subtitle1" sx={{ mb: 2, fontWeight: 'bold', textAlign: 'center' }}>
              性能指标分析
            </Typography>
            
            <Grid container spacing={1} sx={{ mb: 1 }}>
              {/* 指标 */}
              <Grid item xs={12} sm={6}>
                <Paper 
                  elevation={1} 
                  sx={{ 
                    p: 1.5, 
                    bgcolor: '#f5f5f5', 
                    display: 'flex', 
                    flexDirection: 'column',
                    height: '100%'
                  }}
                >
                  <Typography variant="subtitle2" color="text.secondary">敏感度 (真阳性率)</Typography>
                  <Typography variant="h5" color="primary" sx={{ fontWeight: 'bold', mt: 0.5 }}>
                    {(sensitivity * 100).toFixed(2)}%
                  </Typography>
                  <Typography variant="caption" color="text.secondary">
                    识别出的实际阳性样本比例
                  </Typography>
                </Paper>
              </Grid>
              
              <Grid item xs={12} sm={6}>
                <Paper 
                  elevation={1} 
                  sx={{ 
                    p: 1.5, 
                    bgcolor: '#f5f5f5', 
                    display: 'flex', 
                    flexDirection: 'column',
                    height: '100%'
                  }}
                >
                  <Typography variant="subtitle2" color="text.secondary">特异度 (真阴性率)</Typography>
                  <Typography variant="h5" color="primary" sx={{ fontWeight: 'bold', mt: 0.5 }}>
                    {(specificity * 100).toFixed(2)}%
                  </Typography>
                  <Typography variant="caption" color="text.secondary">
                    识别出的实际阴性样本比例
                  </Typography>
                </Paper>
              </Grid>
              
              <Grid item xs={12} sm={6}>
                <Paper 
                  elevation={1} 
                  sx={{ 
                    p: 1.5, 
                    bgcolor: '#f5f5f5', 
                    display: 'flex', 
                    flexDirection: 'column',
                    height: '100%',
                    mt: 1
                  }}
                >
                  <Typography variant="subtitle2" color="text.secondary">假阳性率</Typography>
                  <Typography variant="h5" color="error" sx={{ fontWeight: 'bold', mt: 0.5 }}>
                    {(falsePositiveRate * 100).toFixed(2)}%
                  </Typography>
                  <Typography variant="caption" color="text.secondary">
                    阴性被错误分类为阳性的比例
                  </Typography>
                </Paper>
              </Grid>
              
              <Grid item xs={12} sm={6}>
                <Paper 
                  elevation={1} 
                  sx={{ 
                    p: 1.5, 
                    bgcolor: '#f5f5f5', 
                    display: 'flex', 
                    flexDirection: 'column',
                    height: '100%',
                    mt: 1
                  }}
                >
                  <Typography variant="subtitle2" color="text.secondary">假阴性率</Typography>
                  <Typography variant="h5" color="error" sx={{ fontWeight: 'bold', mt: 0.5 }}>
                    {(falseNegativeRate * 100).toFixed(2)}%
                  </Typography>
                  <Typography variant="caption" color="text.secondary">
                    阳性被错误分类为阴性的比例
                  </Typography>
                </Paper>
              </Grid>
              
              <Grid item xs={12}>
                <Paper 
                  elevation={2} 
                  sx={{ 
                    p: 1.5, 
                    bgcolor: '#e3f2fd', 
                    display: 'flex', 
                    flexDirection: 'column',
                    height: '100%',
                    mt: 1,
                    border: '1px solid #bbdefb'
                  }}
                >
                  <Typography variant="subtitle2" color="text.secondary">模型准确度</Typography>
                  <Typography variant="h4" color="primary" sx={{ fontWeight: 'bold', mt: 0.5 }}>
                    {(accuracy * 100).toFixed(2)}%
                  </Typography>
                  <Typography variant="caption" color="text.secondary">
                    所有样本中被正确分类的比例
                  </Typography>
                </Paper>
              </Grid>
            </Grid>
            
            <Typography variant="caption" sx={{ display: 'block', mt: 1, textAlign: 'right', color: 'text.secondary' }}>
              计算用时: {calculationTime} 毫秒
            </Typography>
          </Paper>
          
          <Box sx={{ mt: 2, textAlign: 'left', width: '100%', maxWidth: '600px' }}>
            <Typography variant="subtitle2" sx={{ mb: 1 }}>混淆矩阵指标解释:</Typography>
            <Typography variant="body2" sx={{ mb: 0.5 }}>• 真阳性 (TP): 正确预测为正类的样本数</Typography>
            <Typography variant="body2" sx={{ mb: 0.5 }}>• 假阳性 (FP): 错误预测为正类的样本数</Typography>
            <Typography variant="body2" sx={{ mb: 0.5 }}>• 真阴性 (TN): 正确预测为负类的样本数</Typography>
            <Typography variant="body2" sx={{ mb: 0.5 }}>• 假阴性 (FN): 错误预测为负类的样本数</Typography>
            <Typography variant="body2" sx={{ mb: 0.5 }}>• 敏感度 = TP / (TP + FN) - 模型正确识别阳性样本的能力</Typography>
            <Typography variant="body2" sx={{ mb: 0.5 }}>• 特异度 = TN / (TN + FP) - 模型正确识别阴性样本的能力</Typography>
            <Typography variant="body2" sx={{ mb: 0.5 }}>• 假阳性率 = FP / (FP + TN) - 与特异度互补，等于 1 - 特异度</Typography>
            <Typography variant="body2" sx={{ mb: 0.5 }}>• 假阴性率 = FN / (TP + FN) - 与敏感度互补，等于 1 - 敏感度</Typography>
          </Box>
        </Box>
      );
    } else {
      // 多分类混淆矩阵
      const maxValue = Math.max(...matrix.flat());
      
      // 计算多分类准确度
      const startTime = performance.now();
      
      // 计算对角线元素之和（正确分类数）
      let correctPredictions = 0;
      let totalPredictions = 0;
      
      // 遍历矩阵计算正确预测数量和总预测数量
      for (let i = 0; i < matrix.length; i++) {
        for (let j = 0; j < matrix[i].length; j++) {
          totalPredictions += matrix[i][j];
          if (i === j) {
            correctPredictions += matrix[i][j];
          }
        }
      }
      
      // 计算多分类准确度
      const accuracy = correctPredictions / totalPredictions;
      
      // 计算每个类别的精确率、召回率和F1分数
      const classMetrics = [];
      
      for (let i = 0; i < matrix.length; i++) {
        let truePositive = matrix[i][i];
        let falsePositive = 0;
        let falseNegative = 0;
        
        // 计算假阳性（该列中非对角线元素之和）
        for (let j = 0; j < matrix.length; j++) {
          if (j !== i) {
            falsePositive += matrix[j][i];
          }
        }
        
        // 计算假阴性（该行中非对角线元素之和）
        for (let j = 0; j < matrix[i].length; j++) {
          if (j !== i) {
            falseNegative += matrix[i][j];
          }
        }
        
        // 计算精确率、召回率和F1分数
        const precision = truePositive / (truePositive + falsePositive) || 0;
        const recall = truePositive / (truePositive + falseNegative) || 0;
        const f1 = 2 * (precision * recall) / (precision + recall) || 0;
        
        classMetrics.push({
          class: i,
          precision,
          recall,
          f1
        });
      }
      
      const endTime = performance.now();
      const calculationTime = (endTime - startTime).toFixed(2);
      
      return (
        <Box sx={{ display: 'flex', flexDirection: 'column', alignItems: 'center' }}>
          <Typography variant="h6" sx={{ mb: 2 }}>多分类混淆矩阵</Typography>
          <Box 
            sx={{ 
              display: 'grid',
              gridTemplateColumns: `repeat(${matrix[0].length + 1}, auto)`,
              gap: 1,
              mb: 2
            }}
          >
            {/* 表头 - 左上角空白单元格 */}
            <Box sx={{ 
              width: 80, 
              height: 40, 
              display: 'flex', 
              justifyContent: 'center', 
              alignItems: 'center',
              bgcolor: '#f5f5f5',
              fontWeight: 'bold',
              borderRadius: 1
            }}>
              实际\预测
            </Box>
            
            {/* 表头 - 预测类别 */}
            {matrix[0].map((_, idx) => (
              <Box key={`pred-${idx}`} sx={{ 
                width: 80, 
                height: 40,
                display: 'flex', 
                justifyContent: 'center', 
                alignItems: 'center',
                bgcolor: '#e3f2fd',
                fontWeight: 'bold',
                borderRadius: 1
              }}>
                类别 {idx}
              </Box>
            ))}
            
            {/* 行标题和数据单元格 */}
            {matrix.map((row, rowIdx) => (
              <React.Fragment key={`row-${rowIdx}`}>
                {/* 行标题 */}
                <Box sx={{ 
                  width: 80, 
                  height: 60,
                  display: 'flex', 
                  justifyContent: 'center', 
                  alignItems: 'center',
                  bgcolor: '#e3f2fd',
                  fontWeight: 'bold',
                  borderRadius: 1
                }}>
                  类别 {rowIdx}
                </Box>
                
                {/* 单元格 */}
                {row.map((cell, colIdx) => {
                  // 计算颜色 - 对角线(正确预测)为绿色，其他为红色，颜色强度基于值
                  const isCorrect = rowIdx === colIdx;
                  const bgColor = isCorrect 
                    ? `rgba(46, 125, 50, ${cell / maxValue})`  // 绿色
                    : `rgba(198, 40, 40, ${cell / maxValue})`; // 红色
                  const textColor = cell / maxValue > 0.5 ? '#fff' : '#000';
                  
                  return (
                    <Paper
                      key={`cell-${rowIdx}-${colIdx}`}
                      elevation={2}
                      sx={{
                        width: 80,
                        height: 60,
                        display: 'flex',
                        justifyContent: 'center',
                        alignItems: 'center',
                        bgcolor: bgColor,
                        color: textColor,
                        fontWeight: 'bold',
                      }}
                    >
                      {cell}
                    </Paper>
                  );
                })}
              </React.Fragment>
            ))}
          </Box>
          
          {/* 添加性能指标表格 */}
          <Paper 
            elevation={2}
            sx={{ 
              width: '100%', 
              maxWidth: '600px', 
              mb: 3, 
              p: 2,
              border: '1px solid #e0e0e0',
              borderRadius: 1
            }}
          >
            <Typography variant="subtitle1" sx={{ mb: 2, fontWeight: 'bold', textAlign: 'center' }}>
              性能指标分析
            </Typography>
            
            {/* 总体准确度 */}
            <Paper 
              elevation={2} 
              sx={{ 
                p: 1.5, 
                bgcolor: '#e3f2fd', 
                display: 'flex', 
                flexDirection: 'column',
                height: '100%',
                mb: 2,
                border: '1px solid #bbdefb'
              }}
            >
              <Typography variant="subtitle2" color="text.secondary">模型准确度</Typography>
              <Typography variant="h4" color="primary" sx={{ fontWeight: 'bold', mt: 0.5 }}>
                {(accuracy * 100).toFixed(2)}%
              </Typography>
              <Typography variant="caption" color="text.secondary">
                所有样本中被正确分类的比例
              </Typography>
            </Paper>
            
            {/* 各类别的指标 */}
            <Typography variant="subtitle2" sx={{ mb: 1 }}>各类别性能指标:</Typography>
            
            <Box 
              sx={{ 
                display: 'grid',
                gridTemplateColumns: 'repeat(4, 1fr)',
                gap: 1,
                mb: 1,
                fontWeight: 'bold',
                bgcolor: '#f5f5f5',
                p: 1,
                borderRadius: 1
              }}
            >
              <Typography variant="body2">类别</Typography>
              <Typography variant="body2">精确率 (Precision)</Typography>
              <Typography variant="body2">召回率 (Recall)</Typography>
              <Typography variant="body2">F1分数</Typography>
            </Box>
            
            {classMetrics.map((metrics, idx) => (
              <Box 
                key={`class-metrics-${idx}`}
                sx={{ 
                  display: 'grid',
                  gridTemplateColumns: 'repeat(4, 1fr)',
                  gap: 1,
                  p: 1,
                  borderBottom: '1px solid #eeeeee'
                }}
              >
                <Typography variant="body2">类别 {metrics.class}</Typography>
                <Typography variant="body2">{(metrics.precision * 100).toFixed(2)}%</Typography>
                <Typography variant="body2">{(metrics.recall * 100).toFixed(2)}%</Typography>
                <Typography variant="body2">{(metrics.f1 * 100).toFixed(2)}%</Typography>
              </Box>
            ))}
            
            <Typography variant="caption" sx={{ display: 'block', mt: 1, textAlign: 'right', color: 'text.secondary' }}>
              计算用时: {calculationTime} 毫秒
            </Typography>
          </Paper>
          
          <Typography variant="caption" sx={{ mt: 1, color: 'text.secondary' }}>
            绿色单元格表示正确预测 (对角线)，红色单元格表示错误预测，颜色强度表示数量
          </Typography>
          
          <Box sx={{ mt: 2, textAlign: 'left', width: '100%', maxWidth: '600px' }}>
            <Typography variant="subtitle2" sx={{ mb: 1 }}>多分类性能指标解释:</Typography>
            <Typography variant="body2" sx={{ mb: 0.5 }}>• 准确度: 所有样本中被正确预测的比例</Typography>
            <Typography variant="body2" sx={{ mb: 0.5 }}>• 精确率 (Precision): 对于每个类别，被预测为该类的样本中实际属于该类的比例</Typography>
            <Typography variant="body2" sx={{ mb: 0.5 }}>• 召回率 (Recall): 对于每个类别，实际属于该类的样本中被正确预测的比例</Typography>
            <Typography variant="body2" sx={{ mb: 0.5 }}>• F1分数: 精确率和召回率的调和平均数，平衡了这两个指标</Typography>
          </Box>
        </Box>
      );
    }
  };

  // 渲染ROC曲线
  const renderRocCurve = () => {
    if (!hasRocCurve) {
      console.log('没有ROC曲线数据可显示:', {
        metrics: metrics?.roc_curve,
        hasRocCurve,
        fpr: metrics?.roc_curve?.fpr,
        tpr: metrics?.roc_curve?.tpr
      });
      return <Typography>没有可用的ROC曲线数据</Typography>;
    }

    console.log('准备渲染ROC曲线，数据:', {
      fprLength: metrics?.roc_curve?.fpr?.length,
      tprLength: metrics?.roc_curve?.tpr?.length,
      auc: metrics?.roc_curve?.auc
    });

    const auc = metrics?.roc_curve?.auc?.toFixed(3) || '未知';
    
    // 准备ECharts的配置
    const option: EChartsOption = {
      title: {
        text: `ROC曲线 (AUC: ${auc})`,
        left: 'center',
        textStyle: {
          fontSize: 16
        }
      },
      tooltip: {
        trigger: 'axis',
        axisPointer: {
          type: 'cross'
        },
        formatter: (params: any) => {
          const fprValue = params[0].value[0].toFixed(3);
          const tprValue = params[0].value[1].toFixed(3);
          return `<div style="text-align:left">
                    <div>假阳性率: ${fprValue}</div>
                    <div>真阳性率: ${tprValue}</div>
                  </div>`;
        }
      },
      grid: {
        left: '5%',
        right: '5%',
        bottom: '12%',
        top: '15%',
        containLabel: true
      },
      xAxis: {
        type: 'value',
        name: '假阳性率 (FPR)',
        nameLocation: 'middle',
        nameGap: 30,
        min: 0,
        max: 1,
        splitLine: {
          lineStyle: {
            type: 'dashed'
          }
        }
      },
      yAxis: {
        type: 'value',
        name: '真阳性率 (TPR)',
        nameLocation: 'middle',
        nameGap: 30,
        min: 0,
        max: 1,
        splitLine: {
          lineStyle: {
            type: 'dashed'
          }
        }
      },
      series: [
        {
          name: 'ROC曲线',
          type: 'line',
          smooth: true,
          symbol: 'circle',
          symbolSize: 6,
          sampling: 'average',
          itemStyle: {
            color: '#1890ff'
          },
          lineStyle: {
            width: 2
          },
          data: metrics?.roc_curve?.fpr.map((fpr: number, index: number) => [
            fpr, 
            metrics.roc_curve?.tpr[index]
          ]) || [],
          markLine: {
            lineStyle: {
              type: 'dashed',
              color: '#888'
            },
            data: [
              [
                { xAxis: 0, yAxis: 0 },
                { xAxis: 1, yAxis: 1 }
              ]
            ],
            label: {
              formatter: '随机猜测基准',
              position: 'middle'
            }
          },
          areaStyle: {
            color: {
              type: 'linear',
              x: 0,
              y: 0,
              x2: 0,
              y2: 1,
              colorStops: [
                {
                  offset: 0,
                  color: 'rgba(24, 144, 255, 0.3)'
                },
                {
                  offset: 1,
                  color: 'rgba(24, 144, 255, 0.1)'
                }
              ]
            }
          }
        }
      ],
      animation: true,
      animationDuration: 1000,
      animationEasing: 'cubicOut'
    };

    console.log('ROC曲线配置已准备:', option);

    return (
      <Box sx={{ display: 'flex', flexDirection: 'column', alignItems: 'center' }}>
        <Box sx={{ width: '100%', height: 400 }}>
          <ReactECharts 
            option={option} 
            style={{ height: '100%', width: '100%' }}
            opts={{ renderer: 'canvas' }}
          />
        </Box>
        
        <Box sx={{ mt: 3, textAlign: 'left', width: '100%', maxWidth: '600px' }}>
          <Typography variant="subtitle2" sx={{ mb: 1 }}>ROC曲线解释:</Typography>
          <Typography variant="body2" sx={{ mb: 0.5 }}>
            • ROC (接收者操作特征) 曲线展示了在不同分类阈值下的真阳性率 (TPR) 和假阳性率 (FPR)
          </Typography>
          <Typography variant="body2" sx={{ mb: 0.5 }}>
            • AUC (曲线下面积) 值越接近1，分类器性能越好
          </Typography>
          <Typography variant="body2" sx={{ mb: 0.5 }}>
            • AUC = 0.5 表示分类器性能等同于随机猜测 (对角线)
          </Typography>
        </Box>
      </Box>
    );
  };

  // 渲染特征重要性
  const renderFeatureImportance = () => {
    if (!hasFeatureImportance) {
      console.log('没有特征重要性数据可显示:', {
        feature_importance,
        hasFeatureImportance
      });
      return <Typography>没有可用的特征重要性数据</Typography>;
    }

    console.log('准备渲染特征重要性，数据:', {
      featureCount: Object.keys(feature_importance!).length,
      sampleFeatures: Object.entries(feature_importance!).slice(0, 3)
    });

    // 对特征重要性进行排序
    const sortedFeatures = Object.entries(feature_importance!)
      .sort(([, valueA], [, valueB]) => valueB - valueA);
    
    const maxValue = Math.max(...Object.values(feature_importance!));
    
    // 准备ECharts配置项
    const option: EChartsOption = {
      title: {
        text: '特征重要性',
        left: 'center',
        textStyle: {
          fontSize: 16
        }
      },
      tooltip: {
        trigger: 'axis',
        axisPointer: {
          type: 'shadow'
        },
        formatter: (params: any) => {
          const featureName = params[0].name;
          const value = params[0].value.toFixed(4);
          return `<div style="text-align:left">
                    <div>${featureName}</div>
                    <div>重要性: ${value}</div>
                  </div>`;
        }
      },
      grid: {
        left: '15%',  // 留出更多空间给特征名称
        right: '5%',
        bottom: '10%',
        top: '15%',
        containLabel: true
      },
      xAxis: {
        type: 'value',
        name: '重要性得分',
        nameLocation: 'middle',
        nameGap: 30,
        splitLine: {
          lineStyle: {
            type: 'dashed'
          }
        },
        axisLabel: {
          formatter: (value: number) => value.toFixed(2)
        }
      },
      yAxis: {
        type: 'category',
        data: sortedFeatures.map(([feature]) => feature),
        axisLabel: {
          interval: 0,
          width: 100,
          overflow: 'truncate'
        }
      },
      series: [
        {
          name: '特征重要性',
          type: 'bar',
          data: sortedFeatures.map(([, value]) => value),
          itemStyle: {
            color: function(params: any) {
              // 根据排名生成颜色渐变
              const colors = [
                '#1890ff', '#52c41a', '#faad14', '#f5222d', '#722ed1',
                '#13c2c2', '#eb2f96', '#fa541c', '#a0d911', '#2f54eb'
              ];
              return colors[params.dataIndex % colors.length];
            },
            borderRadius: [0, 4, 4, 0]
          },
          label: {
            show: true,
            position: 'right',
            formatter: (params: any) => params.value.toFixed(4)
          },
          animationDelay: function (idx: number) {
            return idx * 100;
          }
        }
      ],
      animationEasing: 'elasticOut',
      animationDelayUpdate: function (idx: number) {
        return idx * 5;
      }
    };

    console.log('特征重要性配置已准备:', option);

    return (
      <Box sx={{ display: 'flex', flexDirection: 'column', alignItems: 'center' }}>
        <Box sx={{ width: '100%', height: Math.max(300, sortedFeatures.length * 30) }}>
          <ReactECharts 
            option={option} 
            style={{ height: '100%', width: '100%' }}
            opts={{ renderer: 'canvas' }}
          />
        </Box>
        
        <Box sx={{ mt: 3, textAlign: 'left', width: '100%', maxWidth: '600px' }}>
          <Typography variant="subtitle2" sx={{ mb: 1 }}>特征重要性解释:</Typography>
          <Typography variant="body2" sx={{ mb: 0.5 }}>
            • 特征重要性指示了每个特征对模型预测结果的贡献程度
          </Typography>
          <Typography variant="body2" sx={{ mb: 0.5 }}>
            • 值越高，表示该特征对模型的决策越重要
          </Typography>
          <Typography variant="body2" sx={{ mb: 0.5 }}>
            • 可用于特征选择、模型解释和理解数据中的关键因素
          </Typography>
        </Box>
      </Box>
    );
  };

  // 计算可用的标签页
  const availableTabs = [
    ...(hasConfusionMatrix ? [{ label: '混淆矩阵', render: renderConfusionMatrix }] : []),
    ...(hasRocCurve ? [{ label: 'ROC曲线', render: renderRocCurve }] : []),
    ...(hasFeatureImportance ? [{ label: '特征重要性', render: renderFeatureImportance }] : [])
  ];
  
  // 确保选项卡值有效
  React.useEffect(() => {
    if (tabValue >= availableTabs.length && availableTabs.length > 0) {
      setTabValue(0);
    }
    
    console.log('可用标签页:', {
      availableTabs: availableTabs.map(tab => tab.label),
      currentTab: tabValue,
      hasConfusionMatrix,
      hasRocCurve,
      hasFeatureImportance
    });
  }, [tabValue, availableTabs.length, hasConfusionMatrix, hasRocCurve, hasFeatureImportance]);

  return (
    <Dialog 
      open={open} 
      onClose={onClose}
      maxWidth="md"
      fullWidth
    >
      <DialogTitle>
        <Box sx={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
          模型分析可视化
          <IconButton aria-label="关闭" onClick={onClose} size="small">
            <CloseIcon />
          </IconButton>
        </Box>
      </DialogTitle>
      
      <DialogContent dividers>
        {availableTabs.length > 0 ? (
          <>
            <Tabs 
              value={tabValue} 
              onChange={handleTabChange}
              variant="fullWidth"
              sx={{ borderBottom: 1, borderColor: 'divider', mb: 2 }}
            >
              {availableTabs.map((tab, index) => (
                <Tab key={index} label={tab.label} />
              ))}
            </Tabs>
            
            {availableTabs.map((tab, index) => (
              <TabPanel key={index} value={tabValue} index={index}>
                {tab.render()}
              </TabPanel>
            ))}
          </>
        ) : (
          <Box 
            sx={{ 
              display: 'flex', 
              justifyContent: 'center', 
              alignItems: 'center',
              p: 4
            }}
          >
            <Typography variant="body1" color="text.secondary">
              没有可用的可视化数据。请先执行模型训练和评估。
            </Typography>
          </Box>
        )}
      </DialogContent>
      
      <DialogActions>
        <Button onClick={onClose}>关闭</Button>
      </DialogActions>
    </Dialog>
  );
};

export default ModelVisualizationDialog; 